{% extends "base.html" %}
{% comment 'header' %}
# This file is part of opentaps Smart Energy Applications Suite (SEAS).

# opentaps Smart Energy Applications Suite (SEAS) is free software:
# you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# opentaps Smart Energy Applications Suite (SEAS) is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.

# You should have received a copy of the GNU Lesser General Public License
# along with opentaps Smart Energy Applications Suite (SEAS).
# If not, see <https://www.gnu.org/licenses/>.
{% endcomment %}

{% load static %}

{% block title %}Fabric{% endblock %}

{% block content %}
<div class="container">

  <nav aria-label="breadcrumb">
    <ol class="breadcrumb">
      <li class="breadcrumb-item active" aria-current="page">Fabric</li>
    </ol>
  </nav>

  <div class="card card-body mb-3" >
    <div id="enrolluser">
      <h2>Enroll: <span v-if="isAdminEnrolled">User</span><span v-if="!isAdminEnrolled && isAdmin">Admin</span></h2>
      <br/>
      {% block inner_content %}

      <div class="alert alert-danger mt-3" role="alert" v-if="errors.error" v-cloak>
          ${ errors.error }
      </div>
      <div class="alert alert-success mt-3" role="alert" v-if="successes.success" v-cloak>
        ${ successes.success }
      </div>

      {% if not is_admin %}
        <div class="alert alert-danger flex-grow-1">Only admin is allowed to enroll users</div>
      {% else %}
        <div v-if="isAdminEnrolled && hasWebSocketKey" v-cloak>
          <div class="form-group" v-if="(!success || allowEnrollUserAfterSuccess) && !processing">
            <label for="username">User Name*</label>
            <b-form-input type="text" id="username" :state="usernameState" v-model="username" required></b-form-input>
            <b-form-invalid-feedback id="username">
                User Name is required
            </b-form-invalid-feedback>
          </div>
          <div class="form-group" v-if="(!success || allowEnrollUserAfterSuccess) && !processing">
            <label for="department">Department*</label>
            <b-form-input type="text" id="department" :state="departmentState" v-model="department" required></b-form-input>
            <b-form-invalid-feedback id="department">
                Department is required
            </b-form-invalid-feedback>
          </div>
        </div>

        <div class="mt-3 text-left" v-if="hasWebSocketKey || !isAdminEnrolled">
          <b-button v-if="(!success || allowEnrollUserAfterSuccess) && !processing" variant="primary" v-on:click.stop.prevent="enroll_user()">
            Enroll
          </b-button>
          <div v-if="processing" v-cloak>Please enter <b>${ username || 'admin' }</b> password into the ws-wallet app console.</div>
        </div>
      {% endif %}
      {% endblock inner_content %}

    </div>
    {% include "core/_fabric_websocketkey.html" %}
  </div>
</div>
<script>
(function() {
  {% load js_csrf_token from core_tags %}
  const CSRF_TOKEN = '{% js_csrf_token %}';

  new Vue({
    delimiters: ['${', '}'],
    name: 'enrolluser',
    el: '#enrolluser',
    data() {
      return {
        secType: 'websocket',
        csrfmiddlewaretoken: CSRF_TOKEN,
        errors: {'error': null},
        successes:  {'success': null},
        success: false,
        processing: false,
        isAdmin: {%if is_admin %}true{%else%}false{%endif%},
        isAdminEnrolled: {%if already_enrolled %}true{%else%}false{%endif%},
        allowEnrollUserAfterSuccess: {%if already_enrolled %}false{%else%}true{%endif%},
        hasWebSocketKey: {%if has_web_socket_key %}true{%else%}false{%endif%},
        username: null,
        usernameState: null,
        department: null,
        departmentState: null,
      }
    },
    created: function () {
      eventHub.$on('get_websocketkey', x => {this.hasWebSocketKey = true; this.successes = x;});
      if (this.isAdminEnrolled && !this.hasWebSocketKey) {
        eventHub.$emit('show_get_websocketkey', {});
      }
    },
    methods: {
      enroll_user() {
        this.departmentState = null;
        this.usernameState = null;
        var inputErrors = false;
        if (this.isAdminEnrolled && !this.department) {
          this.departmentState = false;
          inputErrors = true;
        }
        if (this.isAdminEnrolled && !this.username) {
          this.usernameState = false;
          inputErrors = true;
        }
        if (inputErrors) {
          return;
        }
        this.errors = {'error': null};
        this.successes =  {'success': null};
        url = "/opentaps_seas/fabric/enroll.json";
        this.processing = true;
        this.success = false;
        data = new Object();
        data['sec_type'] = this.secType;
        if (this.isAdminEnrolled) {
          data['department'] = this.department;
          data['username'] = this.username;
          data['enroll_user'] = true;

          this.allowEnrollUserAfterSuccess = false;
        }
        axios.post(url, data, {headers: {'X-CSRFToken': this.csrfmiddlewaretoken}})
          .then(x => x.data)
          .then(x => {
            if (x.success) {
              this.successes = {'success': 'Successfully enrolled'};
              this.success = true;
              this.hasWebSocketKey = true;
              if (!this.isAdminEnrolled) {
                this.isAdminEnrolled = true;
              }
             } else if (x.error) {
              this.errors['error'] = x.error;
            } else {
              this.errors['error'] = 'Cannot enroll';
            }
            this.processing = false;
          })
          .catch(err => {
            e = getResponseError(err);
            console.error(e, err);
            this.errors = e;
            this.processing = false;
          });
      }
    },
  });
})();
</script>
{% endblock content %}
